package com.itheima.Dao.Impl;

import com.itheima.Dao.StudentDao;
import com.itheima.domain.Student;
import com.itheima.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements StudentDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public void insert(Student stu) {
            String sql="insert into student values(null,?,?,?)";
            template.update(sql,stu.getUsername(),stu.getAge(),stu.getScore());
    }

    @Override
    public void delete(String sid) {
            String sql="delete from student where sid=?";
            template.update(sql,sid);
    }

    @Override
    public void update(Student newStu) {
            String sql="update student set username=?,age=?,score=? where sid=?";
            template.update(sql,newStu.getUsername(),newStu.getAge(),newStu.getScore(),newStu.getSid());
    }

    @Override
    public  List<Student> selectAll() {
            String sql ="select * from student";
        List<Student> list = template.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        list.forEach(s -> System.out.println(s));

        return list;
    }

    @Override
    public List<Student> selectByCondition(String age, String score) {
        StringBuilder sql = new StringBuilder("select * from student where 1 = 1");

        List<String>list1 =new ArrayList<>();
        if(age!= null && age!= ""){
            sql.append(" and age= ?");
            list1.add(age);
        }
        if(score!= null && score!= ""){
            sql.append(" and score= ?");
            list1.add(score);
        }



        List<Student> list = template.query(sql.toString(), new BeanPropertyRowMapper<Student>(Student.class),list1.toArray());

        return list;
    }


}
